﻿using MediatR;
using WMS.Domain;
using WMS.ErrorCode;
using WMS.Infrasturcture.Interfaces;
using WMS.WebApiRead.Application.Command;

namespace WMS.WebApiRead.Application.Commandhandler
{
    /// <summary>
    /// 部门级联请求处理器
    /// </summary>
    public class WarehousedeptsCascaderCommandhandler : IRequestHandler<WarehousedeptsCascaderCommand, ApiResult<List<CascaderInfo>>>
    {
        private readonly IBaseRepository<WarehouseDept> deptRepository;

        public WarehousedeptsCascaderCommandhandler(IBaseRepository<WarehouseDept> deptRepository)
        {
            this.deptRepository = deptRepository;
        }
        public async Task<ApiResult<List<CascaderInfo>>> Handle(WarehousedeptsCascaderCommand request, CancellationToken cancellationToken)
        {
             var result=await GetCascaderInfos(0);
            return new ApiResult<List<CascaderInfo>>()
            {
                Code = ApiResultEnum.查询成功,
                Message = "查询成功",
                Data = result

            };
        }

        public async Task<List<CascaderInfo>> GetCascaderInfos(int parentId)
        {
           
            //查询父级部门下的所有部门
            var depts =  deptRepository.GetAll().Where(d => d.ParentId == parentId&&!d.IsDeleted).ToList();

            List<CascaderInfo> cascaderInfos = new List<CascaderInfo>();
            foreach (var dept in depts)
            {
                cascaderInfos.Add(new CascaderInfo
                {
                    value = dept.WarehouseDeptId,
                    label = dept.WarehouseDeptName,
                    children = await GetCascaderInfos(dept.WarehouseDeptId)
                });
            }
            //返回部门级联信息
            return cascaderInfos;


        }
    }
}
